package com.dy.yunying.biz.controller.manage;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.dto.SonGameDto;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.entity.ParentGameVersionDO;
import com.dy.yunying.api.req.ParentGameVersionReq;
import com.dy.yunying.api.req.UpdateSonPackReq;
import com.dy.yunying.api.vo.ParentGameVersionVO;
import com.dy.yunying.biz.service.manage.GameService;
import com.dy.yunying.biz.service.manage.ParentGameService;
import com.dy.yunying.biz.service.manage.ParentGameVersionService;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 父游戏版本（母包）
 */
@RestController
@RequestMapping("/parentGame/version")
public class ParentGameVersionController {

	private static Logger logger = LoggerFactory.getLogger(ParentGameVersionController.class);

	@Autowired
	private ParentGameVersionService parentGameVersionService;

	@Autowired
	private ParentGameService parentGameService;

	@Autowired
	private GameService gameService;


	/**
	 * 判断母包版本低于当前版本号 更新中断
	 */
	@RequestMapping("/lastCode")
	public R queryVersionName(@RequestBody ParentGameVersionReq req) {
		try {
			Long gameId = req.getGameId();
			Integer packType = req.getPackType();
			ParentGameVersionDO data = parentGameVersionService.getLatestByGameId(gameId, packType);
			if (data != null) {
				if (req.getCode() >= data.getCode()) {
					return R.ok(data, "成功");
				} else {
					return R.ok(data, "更新中断");
				}
			} else {
				return R.ok("成功");
			}
		} catch (Exception e) {
			logger.error("失败：", e);
			return R.failed(e.getMessage());
		}
	}

	/**
	 * 父游戏下的母包类型列表
	 * @param req
	 * @return
	 */
	@RequestMapping("/getPackTypeList")
	public R getPackTypeList(@RequestBody ParentGameVersionReq req){
		if (Objects.isNull(req.getGameId())){
			return R.failed("未获取到父游戏ID");
		}
		return R.ok(parentGameVersionService.getPackTypeByGameId(req.getGameId()));
	}


	/**
	 * 分页查询渠道包
	 *
	 * @return
	 */
	@SysLog("母包管理")
	@RequestMapping("/page")
	public R page(ParentGameVersionReq req) {
		try {
			Page pge = new Page();
			pge.setSize(req.getSize());
			pge.setCurrent(req.getCurrent());
			IPage<ParentGameVersionVO> data = parentGameVersionService.page(req);
			return R.ok(data, "查询成功");
		} catch (Exception e) {
			logger.error("分页查询渠道包异常：", e);
			return R.failed(e.getMessage());
		}

	}

	/**
	 * 保持母包记录
	 *
	 * @return
	 */
	@SysLog("上传母包")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public R add(@RequestBody ParentGameVersionDO parentGameVersionDO) {
		try {
			logger.info("add-----ParentGameVersionDO:{}", JSON.toJSONString(parentGameVersionDO));
			Integer userId = SecurityUtils.getUser().getId();
			Long gameId = parentGameVersionDO.getGameId();
			ParentGameDO game = parentGameService.getByPK(gameId);
			// 参数校验
			if (userId == null || game == null) {
				return R.failed("参数不合法");
			}
			ParentGameVersionDO data = parentGameVersionService.getLatestByGameId(gameId,null);
			logger.info("add-----data:{}", JSON.toJSONString(data));
			if (data != null && parentGameVersionDO.getCode() < data.getCode()) {
				return R.failed("当前版本过低，请上传最新版本");
			}
			// 参数校验
			if (parentGameVersionDO.getCode() == null || StringUtils.isBlank(parentGameVersionDO.getName()) || StringUtils.isBlank(parentGameVersionDO.getPath())
					|| StringUtils.isBlank(parentGameVersionDO.getSize())) {
				return R.failed("参数不合法");
			}
			ParentGameVersionDO parentGameVersionDB = parentGameVersionService.save(parentGameVersionDO);
			return R.ok(parentGameVersionDB);
		} catch (BusinessException e) {
			logger.error("保持父游戏母包异常：", e);
			return R.failed(e.getMessage());
		} catch (Exception e) {
			logger.error("保持父游戏母包异常：", e);
		}
		return R.failed("操作失败");
	}

	/**
	 * 新增版本基本包
	 *
	 * @return
	 */
	@SysLog("删除母包")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public R add(Long versionId) {
		try {
			// 参数校验
			if (versionId == null) {
				return R.failed("参数不合法");
			}
			parentGameVersionService.deleteByPK(versionId);

			return R.ok();
		} catch (BusinessException e) {
			logger.error("新增版本基本包异常：", e);
			return R.failed(e.getMessage());
		} catch (Exception e) {
			logger.error("新增版本基本包异常：", e);
		}
		return R.failed("操作失败");
	}


	/**
	 * 更新子游戏基础包
	 *
	 * @return
	 */
	@SysLog("更新子游戏基础包")
	@RequestMapping(value = "/updateSonPack", method = RequestMethod.POST)
	public R pack(@RequestBody UpdateSonPackReq req) {
		try {
			Integer userId = SecurityUtils.getUser().getId();
			Long parentVersionId = req.getParentVersionId();
			String gameIds = req.getGameIds();

			// 参数校验
			if (userId == null || parentVersionId == null || StringUtils.isBlank(gameIds)) {
				return R.failed(0, "参数不合法");
			}
			// 字符串 转 列表
			List<Long> gameIdList = Arrays.stream(gameIds.split(","))
					.map(s -> Long.parseLong(s.trim()))
					.collect(Collectors.toList());
			ParentGameVersionDO parentGameVersionDO = parentGameVersionService.getByPK(parentVersionId);
			List<SonGameDto> sonGameList = gameService.selectDtoByPKs(gameIdList);

			if (parentGameVersionDO == null) {
				return R.failed(0, "父游戏母包不存在");
			}

			if (CollectionUtils.isEmpty(sonGameList)) {
				return R.failed(0, "子游戏不存在");
			}
			parentGameVersionService.updateBasePack2(parentGameVersionDO, sonGameList);
			return R.ok();
		} catch (BusinessException e) {
			logger.error("生成渠道包异常：", e);
			return R.failed(0, e.getMessage());
		} catch (Exception e) {
			logger.error("生成渠道包异常：", e);
		}
		return R.failed(0, "操作失败");
	}
}
